package com.yuqing.sentimentapp.yqlist.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseFragment;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.yuqing.sentimentapp.event.CommonEvent;
import com.yuqing.sentimentapp.home.bean.ReplyBean;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.widget.TemplateTimeView;
import com.yuqing.sentimentapp.yqlist.activity.YQReportActivity;
import com.yuqing.sentimentapp.yqlist.bean.YqReportResultBean;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DateTimePicker;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by shenhe on 2019/4/19.
 */
public class RescueTemplateFragment extends BaseFragment {
    @BindView(R.id.et_url)
    EditText mEtUrl;
    @BindView(R.id.et_address)
    EditText mEtAddress;
    @BindView(R.id.rb_verifing)
    RadioButton mRbVerifing;
    @BindView(R.id.rb_verified)
    RadioButton mRbVerified;
    @BindView(R.id.rg_verify)
    RadioGroup mRgVerify;
    @BindView(R.id.rb_policeing)
    RadioButton mRbPoliceing;
    @BindView(R.id.rb_policed)
    RadioButton mRbPoliced;
    @BindView(R.id.rg_police)
    RadioGroup mRgPolice;
    @BindView(R.id.layout_alarm)
    LinearLayout mLayoutAlarm;
    @BindView(R.id.tt_police_time)
    TemplateTimeView mTtPoliceTime;
    @BindView(R.id.et_person_num)
    EditText mEtPersonNum;
    @BindView(R.id.et_car_num)
    EditText mEtCarNum;
    @BindView(R.id.layout_police)
    LinearLayout mLayoutPolice;
    @BindView(R.id.rb_return_halfway)
    RadioButton mRbReturnHalfway;
    @BindView(R.id.rb_present_unprocessed)
    RadioButton mRbPresentUnprocessed;
    @BindView(R.id.rg_unprocessed)
    RadioGroup mRgUnprocessed;
    @BindView(R.id.rb_present_precessing)
    RadioButton mRbPresentPrecessing;
    @BindView(R.id.rb_present_precessed)
    RadioButton mRbPresentPrecessed;
    @BindView(R.id.rg_process)
    RadioGroup mRgProcess;
    @BindView(R.id.layout_process)
    LinearLayout mLayoutProcess;
    @BindView(R.id.tt_present_time)
    TemplateTimeView mTtPresentTime;
    @BindView(R.id.layout_present_time)
    LinearLayout mLayoutPresentTime;
    @BindView(R.id.tt_end_time)
    TemplateTimeView mTtEndTime;
    @BindView(R.id.layout_end_time)
    LinearLayout mLayoutEndTime;
    @BindView(R.id.et_hurt_num)
    EditText mEtHurtNum;
    @BindView(R.id.et_dead_num)
    EditText mEtDeadNum;
    @BindView(R.id.et_trapped_num)
    EditText mEtTrappedNum;
    @BindView(R.id.et_losing_contact_num)
    EditText mEtLossNum;
    @BindView(R.id.layout_casualties)
    LinearLayout mLayoutCasualties;
    @BindView(R.id.et_remark)
    EditText mEtRemark;
    @BindView(R.id.btn_report)
    Button mBtnReport;

    private String linkId;//舆情id
    private String title;//标题
    private String url;//链接
    private String isVerified;//是否核实
    private String isAlarm;//是否接警
    private String isOut;//是否出警
    private String alarmTime;//出警时间
    private String personCount;//出警人数
    private String carCount;//出警车辆
    private String arrivalTime;//到场时间
    private String finishTime;//结束时间
    private String injuredCount;//受伤人数
    private String deathCount;//死亡人数
    private String trappedCount;//被困人数
    private String lossCount;//失联人数
    private String remark;//说明
    private String address;//时间发生地址
    private String content;//内容
    private String replyId;
    private boolean isReportAgain;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_rescue_template;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initParamsData();
        checkVerifyBtn();
        checkPoliceBtn();
        checkProcessBtn();
    }

    private void initParamsData() {
        linkId = ((YQReportActivity) getActivity()).getYqLinkId();
        title = ((YQReportActivity) getActivity()).getYqTitle();
        url = ((YQReportActivity) getActivity()).getYqUrl();
        content = ((YQReportActivity) getActivity()).getYqContent();

        mEtUrl.setText(url);
    }

    private void checkPoliceBtn() {
        mRgPolice.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_policeing) {//未出警
                hidePoliceTimeView();
            } else {//已经出警
                showPoliceTimeView();
            }
        });
    }

    private void checkVerifyBtn() {
        mRgVerify.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_verifing) {//未核实
                hideAll();
            } else {//已经核实
                showPoliceView();
            }
        });
    }

    private void checkProcessBtn() {
        mRgUnprocessed.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_return_halfway && mRbReturnHalfway.isChecked()) {//中途返回
                isOut = "0";
                hideProcessAll();
            } else if (checkedId == R.id.rb_present_unprocessed && mRbPresentUnprocessed.isChecked()) {//到场未处置
                isOut = "1";
                showProcessAll();
            }
        });
        mRgProcess.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_present_precessing && mRbPresentPrecessing.isChecked()) {//当场处置中
                isOut = "2";
                hideEndTimeOnly();
            } else if (checkedId == R.id.rb_present_precessed && mRbPresentPrecessed.isChecked()) {//到场处置完
                isOut = "3";
                showProcessAll();
            }
        });
    }

    private void hideEndTimeOnly() {
        mLayoutPresentTime.setVisibility(View.VISIBLE);
        mLayoutEndTime.setVisibility(View.GONE);
        mLayoutCasualties.setVisibility(View.VISIBLE);
    }

    private void showProcessAll() {
        mLayoutPresentTime.setVisibility(View.VISIBLE);
        mLayoutEndTime.setVisibility(View.VISIBLE);
        mLayoutCasualties.setVisibility(View.VISIBLE);
    }

    private void hideProcessAll() {
        mLayoutPresentTime.setVisibility(View.GONE);
        mLayoutEndTime.setVisibility(View.GONE);
        mLayoutCasualties.setVisibility(View.GONE);
    }

    /**
     * 点击未核实，未出警都要置为true，联动状态
     */
    private void hideAll() {
        mLayoutAlarm.setVisibility(View.GONE);
        //未出警置为true
        mRbPoliceing.setChecked(true);
        isVerified = "0";

    }

    /**
     * 点击已核实，未出警都要置为true，联动状态
     */
    private void showPoliceView() {
        mLayoutAlarm.setVisibility(View.VISIBLE);
        //未出警置为true
        mRbPoliceing.setChecked(true);

        isVerified = "1";
    }

    /**
     * 点击未出警时，警情处理状态置空
     */
    private void hidePoliceTimeView() {
        mLayoutPolice.setVisibility(View.GONE);
        mLayoutProcess.setVisibility(View.GONE);
        //警情处置状态清空
        mRgUnprocessed.clearCheck();
        mRgProcess.clearCheck();
        //隐藏现场情况
        hideProcessAll();

        isAlarm = "0";
    }

    /**
     * 点击已出警时，警情处理状态置空
     */
    private void showPoliceTimeView() {
        mLayoutPolice.setVisibility(View.VISIBLE);
        mLayoutProcess.setVisibility(View.VISIBLE);
        //警情处置状态清空
        mRgUnprocessed.clearCheck();
        mRgProcess.clearCheck();
        //隐藏现场情况
        hideProcessAll();

        isAlarm = "1";
    }

    @Override
    protected void initPresenter() {

    }

    @OnClick({R.id.rb_return_halfway, R.id.rb_present_unprocessed, R.id.rb_present_precessing, R.id.rb_present_precessed, R.id.btn_report, R.id.tt_police_time, R.id.tt_present_time, R.id.tt_end_time})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.rb_return_halfway:
                mRgProcess.clearCheck();
                break;
            case R.id.rb_present_unprocessed:
                mRgProcess.clearCheck();
                break;
            case R.id.rb_present_precessing:
                mRgUnprocessed.clearCheck();
                break;
            case R.id.rb_present_precessed:
                mRgUnprocessed.clearCheck();
                break;
            case R.id.tt_police_time:
                showTimeSelectorView(0);
                break;
            case R.id.tt_present_time:
                showTimeSelectorView(1);
                break;
            case R.id.tt_end_time:
                showTimeSelectorView(2);
                break;
            case R.id.btn_report:
                report();
                break;
        }
    }

    private void showTimeSelectorView(int type) {
        DateTimePicker picker = new DateTimePicker(getActivity(), DateTimePicker.HOUR_24);//24小时值
        picker.setDateRangeStart(1910, 1, 1);//日期起点
        picker.setDateRangeEnd(2099, 1, 1);//日期终点
        picker.setTimeRangeStart(0, 0);//时间范围起点
        picker.setTimeRangeEnd(23, 59);//时间范围终点
        picker.setTextColor(getResources().getColor(R.color.color_0d7dff), getResources().getColor(R.color.color_666666));
        picker.setCancelTextColor(getResources().getColor(R.color.color_0d7dff));
        picker.setSubmitTextColor(getResources().getColor(R.color.color_0d7dff));
        picker.setLineColor(getResources().getColor(R.color.color_0d7dff));
        picker.setOnDateTimePickListener((DateTimePicker.OnYearMonthDayTimePickListener) (year, month, day, hour, minute) -> {
            //year:年，month:月，day:日，hour:时，minute:分
            String time = year + "-" + month + "-" + day + " "
                    + hour + ":" + minute;
            switch (type) {
                case 0:
                    mTtPoliceTime.setTemplateTime(time);
                    break;
                case 1:
                    mTtPresentTime.setTemplateTime(time);
                    break;
                case 2:
                    mTtEndTime.setTemplateTime(time);
                    break;
            }
        });
        picker.show();
    }

    private void report() {
        if (TextUtils.equals("1", isVerified)) {//已核实
            if (TextUtils.equals("1", isAlarm)) {//已出警
                alarmTime = mTtPoliceTime.getTemplateTime();
                personCount = mEtPersonNum.getText().toString().trim();
                carCount = mEtCarNum.getText().toString().trim();
                if (!TextUtils.isEmpty(isOut)) {
                    switch (isOut) {
                        case "0"://中途返回

                            break;
                        case "1"://到场未处置
                            arrivalTime = mTtPresentTime.getTemplateTime();
                            finishTime = mTtEndTime.getTemplateTime();
                            injuredCount = mEtHurtNum.getText().toString().trim();
                            deathCount = mEtDeadNum.getText().toString().trim();
                            trappedCount = mEtTrappedNum.getText().toString().trim();
                            lossCount = mEtLossNum.getText().toString().trim();
                            remark = mEtRemark.getText().toString().trim();
                            break;
                        case "2"://到场处置中
                            arrivalTime = mTtPresentTime.getTemplateTime();
                            injuredCount = mEtHurtNum.getText().toString().trim();
                            deathCount = mEtDeadNum.getText().toString().trim();
                            trappedCount = mEtTrappedNum.getText().toString().trim();
                            lossCount = mEtLossNum.getText().toString().trim();
                            remark = mEtRemark.getText().toString().trim();
                            break;
                        case "3"://到场处置完
                            arrivalTime = mTtPresentTime.getTemplateTime();
                            finishTime = mTtEndTime.getTemplateTime();
                            injuredCount = mEtHurtNum.getText().toString().trim();
                            deathCount = mEtDeadNum.getText().toString().trim();
                            trappedCount = mEtTrappedNum.getText().toString().trim();
                            lossCount = mEtLossNum.getText().toString().trim();
                            remark = mEtRemark.getText().toString().trim();
                            break;
                    }
                }
            } else {//未出警

            }
        } else {//未核实
            //直接上报

        }
        address = mEtAddress.getText().toString().trim();
        remark = mEtRemark.getText().toString().trim();
        Map<String, String> param = new HashMap<>();
        param.put("reply.replyType", "B");
        if (isReportAgain) {
            param.put("reply.id", replyId);
        }
        param.put("reply.linkId", linkId == null ? "" : linkId);
        param.put("reply.title", title == null ? "" : title);
        param.put("reply.url", url == null ? "" : url);
        param.put("reply.isVerified", isVerified == null ? "0" : isVerified);
        param.put("reply.isAlarm", isAlarm == null ? "0" : isAlarm);
        param.put("reply.isOut", isOut == null ? "0" : isOut);
        param.put("reply.alarmTime", alarmTime == null ? "" : alarmTime);
        param.put("reply.personCount", personCount == null ? "" : personCount);
        param.put("reply.carCount", carCount == null ? "" : carCount);
        param.put("reply.arrivalTime", arrivalTime == null ? "" : arrivalTime);
        param.put("reply.finishTime", finishTime == null ? "" : finishTime);
        param.put("reply.injuredCount", injuredCount == null ? "" : injuredCount);
        param.put("reply.deathCount", deathCount == null ? "" : deathCount);
        param.put("reply.trappedCount", trappedCount == null ? "" : trappedCount);
        param.put("reply.lossCount", lossCount == null ? "" : lossCount);
        param.put("reply.remark", remark == null ? "" : remark);
        param.put("reply.address", address == null ? "" : address);
        param.put("reply.content", content == null ? "" : content);
        postReport(param, isReportAgain);
    }

    private void postReport(Map<String, String> param, boolean isReportAgain) {
        ModuleManager.getInstance().postReportDataResult(getActivity(), param, isReportAgain)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<YqReportResultBean>() {
                    @Override
                    protected void hideDialog() {
                        stopProgressDialog();
                    }

                    @Override
                    protected void showDialog() {
                        startProgressDialog();
                    }

                    @Override
                    protected void onSuccess(YqReportResultBean baseBean) {
                        ToastUtil.showShort("上报成功");
                        EventBus.getDefault().post(new CommonEvent(-1 , ((YQReportActivity) getActivity()).getPosition() + "", baseBean));
                        getActivity().finish();
                    }

                    @Override
                    protected void onFailure(String message) {
                        ToastUtil.showShort(message);
                    }
                });
    }

    public void updateData(ReplyBean reply, int state) {
        isReportAgain = state == 1;
        //重置核实、出警状态
        mRgVerify.clearCheck();
        mRgPolice.clearCheck();

        replyId = reply.getId();
        isVerified = reply.getIsVerified();//是否核实
        alarmTime = reply.getAlarmTime();//出警时间
        personCount = reply.getPersonCount();//出警人数
        carCount = reply.getCarCount();//出警车辆
        arrivalTime = reply.getArrivalTime();//到场时间
        finishTime = reply.getFinishTime();//结束时间
        injuredCount = reply.getInjuredCount();//受伤人数
        deathCount = reply.getDeathCount();//死亡人数
        trappedCount = reply.getTrappedCount();//被困人数
        lossCount = reply.getLossCount();//失踪人数
        remark = reply.getRemark();//说明
        address = reply.getAddress();//时间发生地址
        content = reply.getContent();//内容

        if (!TextUtils.isEmpty(isVerified) && TextUtils.equals("1", isVerified)) {
            mRbVerified.setChecked(true);
            isAlarm = reply.getIsAlarm();//是否接警
            if (!TextUtils.isEmpty(isAlarm) && TextUtils.equals("1", isAlarm)) {
                mRbPoliced.setChecked(true);
                mTtPoliceTime.setTemplateTime(alarmTime);
                mEtPersonNum.setText(personCount);
                mEtCarNum.setText(carCount);
                isOut = reply.getIsOut();//是否出警
                if (!TextUtils.isEmpty(isOut)) {
                    switch (isOut) {
                        case "0":
                            mRbReturnHalfway.setChecked(true);
                            break;
                        case "1":
                            mRbPresentUnprocessed.setChecked(true);
                            mTtPresentTime.setTemplateTime(arrivalTime);
                            mTtEndTime.setTemplateTime(finishTime);
                            mEtHurtNum.setText(injuredCount);
                            mEtDeadNum.setText(deathCount);
                            mEtTrappedNum.setText(trappedCount);
                            mEtLossNum.setText(lossCount);
                            break;
                        case "2":
                            mRbPresentPrecessing.setChecked(true);
                            mTtPresentTime.setTemplateTime(arrivalTime);
                            mEtHurtNum.setText(injuredCount);
                            mEtDeadNum.setText(deathCount);
                            mEtTrappedNum.setText(trappedCount);
                            mEtLossNum.setText(lossCount);
                            break;
                        case "3":
                            mRbPresentPrecessed.setChecked(true);
                            mTtPresentTime.setTemplateTime(arrivalTime);
                            mTtEndTime.setTemplateTime(finishTime);
                            mEtHurtNum.setText(injuredCount);
                            mEtDeadNum.setText(deathCount);
                            mEtTrappedNum.setText(trappedCount);
                            mEtLossNum.setText(lossCount);
                            break;
                    }
                }
            } else {//未出警
                mRbPoliceing.setChecked(true);
            }
        } else {//未核实
            mRbVerifing.setChecked(true);
        }
        mEtAddress.setText(address);
        mEtRemark.setText(remark);
        mBtnReport.setText(state == 1 ? "重报" : "上报");
    }
}
